package com.sicaupqroo.sica;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.Parser;

import com.sicaupqroo.sica.Login.asynclogin;
import com.sicaupqroo.sica.R.string;
import com.sicaupqroo.sica.library.Httppostaux;

import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class Inicio extends Activity {
	// String user;
	// TextView txt_usr, logoff;
	TextView logoff;

	String line = null;

	int ct_id;
	String[] ct_name = null;
	String[] apellidos = null;
	ArrayAdapter<String> adapter;

	String result = null;
	InputStream is = null;
	StringBuilder sb = null;
	AutoCompleteTextView txtbusqueda;
	LinearLayout ln;
	Httppostaux post;
	ImageButton btnscanear;
	String radiomatricula;
	RadioButton rA, rR, rF;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_inicio);

		txtbusqueda = (AutoCompleteTextView) findViewById(R.id.txtBusqueda);
		btnscanear = (ImageButton) findViewById(R.id.scanear);
		ln = (LinearLayout) findViewById(R.id.Botones);
		rA = (RadioButton) findViewById(R.id.rdAsistencia);
		rR = (RadioButton) findViewById(R.id.rdRetardo);
		rF = (RadioButton) findViewById(R.id.rdFalta);

		ln.setVisibility(LinearLayout.INVISIBLE);
		new BusquedaAlumno().execute();

		// txt_usr= (TextView) findViewById(R.id.usr_name);
		logoff = (TextView) findViewById(R.id.logoff);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			// user = extras.getString("user");
		} else {
			// user="error";
		}

		// txt_usr.setText(user);
		btnscanear.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {
				IntentIntegrator scanIntegrator = new IntentIntegrator(
						Inicio.this);
				scanIntegrator.initiateScan();

			}
		});

		logoff.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {

				finish();
			}
		});

		txtbusqueda.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				String matricula = (String) arg0.getItemAtPosition(arg2);
				StringTokenizer tokens = new StringTokenizer(matricula);
				String[] datos = new String[3];
				int i = 0;
				while (tokens.hasMoreTokens()) {
					datos[i] = tokens.nextToken();
					i++;
				}
				// Log.d("ID : ",String.valueOf(datos[0]));

				new AsistenciaAlumno().execute(datos[0], datos[1], datos[2]);
				radiomatricula = datos[0];
				// radiobotones();
				ln.setVisibility(LinearLayout.VISIBLE);

			}
		});

		txtbusqueda.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {

				if (keyCode == KeyEvent.KEYCODE_DEL) {

					ln.setVisibility(LinearLayout.INVISIBLE);
				}
				return false;
			}
		});
	}

	public void ClicA(View view) {
		new updateEstado().execute(radiomatricula,"a");
	}

	public void ClicR(View view) {
		new updateEstado().execute(radiomatricula,"r");
	}

	public void ClicF(View view) {
		new updateEstado().execute(radiomatricula,"f");

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			// no hacemos nada.
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	public void onActivityResult(int respuestaDeCodigo, int codigoResultante,
			Intent intent) {
		IntentResult scanningResult = IntentIntegrator.parseActivityResult(
				respuestaDeCodigo, codigoResultante, intent);
		String Contenido = scanningResult.getContents();

		Contenido = Contenido.replace(" ", "");
		// Toast toast1 =
		// Toast.makeText(getApplicationContext(),"Resultado: "+Contenido,
		// Toast.LENGTH_SHORT);
		// toast1.show();
		new AsistenciaAlumno().execute(Contenido);

		// buscarProducto(Contenido);
	}

	public void radiobotones() {
		String countryName[] = { "Asistencia", "Retardo", "Falta" };
		for (int k = 1; k <= 1; k++) {
			// create text button
			TextView title = new TextView(this);
			// title.setText("");
			title.setTextColor(Color.BLUE);
			ln.addView(title);
			// create radio button
			final RadioButton[] rb = new RadioButton[3];
			RadioGroup rg = new RadioGroup(this);
			rg.setOrientation(RadioGroup.VERTICAL);
			for (int i = 0; i < 3; i++) {
				rb[i] = new RadioButton(this);
				rg.addView(rb[i]);
				rb[i].setText(countryName[i]);

			}
			ln.addView(rg);
		}
	}

	public void GetAlumnos() {
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(
					"http://192.168.1.10:8080/SICA/Lista_General/busqueda_alumnos.php");
			// List<NameValuePair> nameValuePairs = new
			// ArrayList<NameValuePair>(2);
			// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection" + e.toString());
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			sb = new StringBuilder();
			sb.append(reader.readLine() + "\n");
			String line = "0";
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result = sb.toString();
		} catch (Exception e) {
			Log.e("log_tag", "Error converting result " + e.toString());

		}

		JSONArray jArray;
		try {
			jArray = new JSONArray(result);
			JSONObject json_data = null;

			ct_name = new String[jArray.length()];
			apellidos = new String[jArray.length()];

			for (int i = 0; i < jArray.length(); i++) {
				json_data = jArray.getJSONObject(i);
				ct_id = json_data.getInt("id");
				ct_name[i] = json_data.getString("matricula") + " "
						+ json_data.getString("nombre") + " "
						+ json_data.getString("apellidos");

			}
		} catch (JSONException e1) {
			Toast.makeText(getBaseContext(), "No hay alumnos",
					Toast.LENGTH_LONG).show();

		} catch (ParseException e1) {
			e1.printStackTrace();

		}
	}

	public int SetAlumnos(String matricula) {
		int logstatus = -1;


		// ------------------------------------
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(
					"http://192.168.1.10:8080/SICA/Lista_General/Asistencia.php");
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("matricula", matricula));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection" + e.toString());
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			sb = new StringBuilder();
			sb.append(reader.readLine() + "\n");
			String line = "0";
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result = sb.toString();
		} catch (Exception e) {
			Log.e("log_tag", "Error converting result " + e.toString());

		}

		JSONArray jdata = null;

		try {
			jdata = new JSONArray(result);
			Log.e("Matricula", " " + jdata);

			// ----------------------------------

			if (jdata != null && jdata.length() > 0) {

				JSONObject json_data;
				try {
					json_data = jdata.getJSONObject(0);
					logstatus = json_data.getInt("logstatus");// accedemos al
																// valor
					Log.e("loginstatus", "logstatus= " + logstatus);// muestro
																	// por log
																	// que
																	// obtuvimos
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				// validamos el valor obtenido
				if (logstatus == 0) {// [{"logstatus":"0"}]
					Log.e("loginstatus ", "invalido");
					return 0;
				} else if (logstatus == 2) {// [{"logstatus":"2"}]
					Log.e("loginstatus ", "invalido");
					return 2;
				}
				if (logstatus == 3) {// [{"logstatus":"2"}]
					Log.e("loginstatus ", "invalido");
					return 3;
				} else {// [{"logstatus":"1"}]
					Log.e("loginstatus ", "valido");
					return 1;
				}

			} else { // json obtenido invalido verificar parte WEB.
				Log.e("JSON  ", "ERROR");
				return 0;
			}
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			return 0;
		}
	}
	
	public int UpdateEstadoAlumnos(String matricula,String estado) {
		int logstatus = -1;
		// ------------------------------------
				try {
					HttpClient httpclient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost(
							"http://192.168.1.10:8080/SICA/Lista_General/updateEstado.php");
					List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
					nameValuePairs.add(new BasicNameValuePair("matricula", matricula));
					nameValuePairs.add(new BasicNameValuePair("estado", estado));
					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
					HttpResponse response = httpclient.execute(httppost);
					HttpEntity entity = response.getEntity();
					is = entity.getContent();
				} catch (Exception e) {
					Log.e("log_tag", "Error in http connection" + e.toString());
				}

				try {
					BufferedReader reader = new BufferedReader(new InputStreamReader(
							is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";
					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
				} catch (Exception e) {
					Log.e("log_tag", "Error converting result " + e.toString());

				}

				JSONArray jdata = null;

				try {
					jdata = new JSONArray(result);
					Log.e("Matricula", " " + jdata);

					// ----------------------------------

					if (jdata != null && jdata.length() > 0) {

						JSONObject json_data;
						try {
							json_data = jdata.getJSONObject(0);
							logstatus = json_data.getInt("logstatus");// accedemos al
																		// valor
							Log.e("loginstatus", "logstatus= " + logstatus);// muestro
																			// por log
																			// que
																			// obtuvimos
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						// validamos el valor obtenido
						if (logstatus == 1) {// [{"logstatus":"0"}]
							Log.e("loginstatus ", "valido");
							return 1;
						} else {// [{"logstatus":"2"}]
							Log.e("loginstatus ", "invalido");
							return 0;
						}
						

					} else { // json obtenido invalido verificar parte WEB.
						Log.e("JSON  ", "ERROR");
						return 0;
					}
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					return 0;
				}
	}

	class BusquedaAlumno extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			GetAlumnos();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			Log.e("onPostExecute=", "" + result);
			runOnUiThread(new Runnable() {
				public void run() {
					adapter = new ArrayAdapter<String>(Inicio.this,
							android.R.layout.select_dialog_singlechoice,
							ct_name);

					txtbusqueda.setThreshold(1);
					txtbusqueda.setAdapter(adapter);

				}
			});

		}
	}

	class AsistenciaAlumno extends AsyncTask<String, String, String> {
		String matricula, nombre, apellido;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		protected String doInBackground(String... params) {
			matricula = params[0];
			// nombre=params[1];
			// apellido=params[2];
			int consulta = SetAlumnos(matricula);
			String tipo = null;

			if (consulta == 1) {
				tipo = "1"; // login valido
			}
			if (consulta == 2) {
				tipo = "2";// login invalido
			}
			if (consulta == 3) {
				tipo = "3";// login invalido
			}
			if (consulta == 0) {
				tipo = "0";
			}
			return tipo;

		}

		protected void onPostExecute(String result) {
			Log.e("onPostExecute=", "" + result);
			if (result.equals("1")) {
				Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
				vibrator.vibrate(200);
				Toast toast1 = Toast.makeText(getApplicationContext(),
						"Registrado Correctamente", Toast.LENGTH_SHORT);
				toast1.show();
			}
			if (result.equals("2")) {
				Toast toast1 = Toast.makeText(getApplicationContext(),
						"Error: El horario de clases finalizo",
						Toast.LENGTH_SHORT);
				toast1.show();
			}
			if (result.equals("3")) {
				Toast toast1 = Toast.makeText(getApplicationContext(),
						"Matricula Incorrecta", Toast.LENGTH_SHORT);
				toast1.show();
			}
			if (result.equals("0")) {
				Toast toast1 = Toast.makeText(getApplicationContext(),
						"Error: El alumno  ya fue registrado hoy",
						Toast.LENGTH_SHORT);
				toast1.show();
			}

		}
	}
	
	
	class updateEstado extends AsyncTask<String, String, String> {
		String matricula, estado;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		protected String doInBackground(String... params) {
			matricula = params[0];
			estado=params[1];
			// nombre=params[1];
			// apellido=params[2];
			int consulta = UpdateEstadoAlumnos(matricula,estado);
			String tipo = null;

			if (consulta == 1) {
				tipo = "1"; // login valido
			}
			if (consulta == 0) {
				tipo = "0";
			}
			return tipo;

		}

		protected void onPostExecute(String result) {
			Log.e("onPostExecute=", "" + result);
			if (result.equals("1")) {
				Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
				vibrator.vibrate(200);
				Toast toast1 = Toast.makeText(getApplicationContext(),
						"Editado Correctamente", Toast.LENGTH_SHORT);
				toast1.show();
			}
			if (result.equals("0")) {
				Toast toast1 = Toast.makeText(getApplicationContext(),
						"Error: Fallo al editar",
						Toast.LENGTH_SHORT);
				toast1.show();
			}

		}
	}
	
	

}